/* 通用相关 */
var loading = require('./loading.js');
var user = require('./user.js');
var common = {
    /*
     * 初始化导航
     * index: 导航选中索引
     */
    initNav: function (index) {
        var navHtml = '';
        navHtml += '<ul id="breadcrumb">';
        navHtml += '    <li><a href="javascript:;" data-page="1"><span class="icon icon-home"> </span>首页</a></li>';
        navHtml += '    <li><a href="javascript:;" data-page="2"><span class="icon icon-file"> </span> 新建FOF</a></li>';
        navHtml += '    <li><a href="javascript:;" data-page="4"><span class="icon icon-user"></span> 资产/策略 配置</a></li>';
        navHtml += '    <li><a href="javascript:;" data-page="5"><span class="icon icon-filter"> </span> 基金筛选</a></li>';
        navHtml += '    <li><a href="javascript:;" data-page="7"><span class="icon icon-magic"> </span> 组合优化</a></li>';
        navHtml += '    <li><a href="javascript:;"><span class="icon icon-table"> </span> FOF展示</a></li>';
        navHtml += '</ul>';
        if ($('#breadcrumb').size() == 0) {
            $('#container').prepend(navHtml);
        }
        if (typeof index != 'undefined') {
            $('#breadcrumb').find('li').removeClass('on').eq(index).addClass('on');
        }
        $('#breadcrumb').off().on('click', 'a', function () {
            console.log('breadcrumb click...');
            var p = $(this).attr('data-page');
            var page = require('./page.js');
            if (typeof p != 'undefined' && p < window['fofPage']) {
                page.showPage(p);
            }
        });
        $('#progressHead').off().on('click', 'a', function () {
            var height = $('#progress').height();
            console.log('height:' + height);
            if (height > 28) {
                $('#progress').animate({height: 30}, 200);
                $(this).html('展开');
            } else {
                var childrenHeight = 0;
                $('#progress').children().each(function () {
                    childrenHeight += $(this).height();
                });
                $('#progress').animate({height: childrenHeight}, 100);
                $(this).html('收起');
            }
        });
    },
    /*
     * 静态数据集合
     */
    staticData: {
        profitType: '收益类型',
        productType: '产品类型',
        fofStatus: {
            1: '完全公开',
            2: '公司内部可见',
            3: '只有指定用户可见',
            4: '私有，只有owner可见'
        },
        configOrCombinationParam: {
            iteration: {
                title: '有效前沿上的点数',
                list: [
                    {
                        text: '100',
                        value: '1',
                        name: 'iterationNumber',
                        checked: true
                    },
                    {
                        text: '1000',
                        value: '2'
                    },
                    {
                        text: '3000',
                        value: '3'
                    }
                ]
            },
            backLength: {
                title: '计算回溯时长',
                list: [
                    {
                        text: '1年',
                        value: '1',
                        name: 'backLength'
                    },
                    {
                        text: '3年',
                        value: '2',
                        checked: true
                    },
                    {
                        text: '5年',
                        value: '3'
                    }
                ]
            }
        }
    },
    /*
     * 后台服务url参数
     */
    dataUrl: {
        userLogin: 'api/fof/userInfo/login/',
        userFof: 'api/fof/fofInfo/userFof/',
        fofTypeList: 'api/fof/productType/fofTypeList',
        getAssetOrStrategy: 'api/fof/fofInfo/getAssetOrStrategy',
        fundFilter: 'api/fof/fofInfo/fundFilter',
        fundCombination: 'api/fof/fofFundIndicator/fundCombination',
        assetOrStrategyStart: 'api/fof/fofInfo/assetOrStrategyStart',
        assetOrStrategyResult: 'api/fof/fofInfo/assetOrStrategyResult',
        assetOrStrategyResultCustom: 'api/fof/fofInfo/assetOrStrategyResultCustom',
        viewPointCal: 'api/fof/fofInfo/viewPointCal',
        fundsTrend: 'api/fof/fofInfo/fundsTrend',
        create: 'api/fof/fofInfo/create',
        getFofNav: 'api/fof/fofResult/getFofNav',
        getFofDrawDown: 'api/fof/fofResult/getFofDrawDown',
        getFofWeight: 'api/fof/fofResult/getFofResult',
        getFofAssetConf: 'api/fof/fofResult/getFofAssetConf'
    },
    /*
     * 请求后台数据
     */
    getData: function (data) {
        if (!data || !data.path || !data.callback) {
            return;
        }
        //var host = 'http://192.168.1.117:8888/';
        //var host = 'http://123.56.90.38:8080/';
        var host = 'http://fof.luger.me/';
        var testHost = common.getKey(window.location.href, 'host');
        if (testHost) {
            host = testHost;
        }
        var url = host + this.dataUrl[data.path];
        if (data.extra) {
            url += data.extra;
        }
        url += (url.indexOf('?') > -1 ? '&' : '?') + 'callback=' + data.callback + '&uid=' + (user.getUser().id || '');
        console.log('url:', url);
        $.getScript(url);
    },
    /*
     * 过滤一下服务器数据 只解析 code为200的数据
     */
    filterData: function (json, dataKey) {
        if (json && json.code && json.code == 200) {
            var data = json.data;
            if (dataKey) {
                if (data[dataKey]) {
                    return data[dataKey];
                }
            }
            return data;
        } else {
            console.log(json);
            if (json && json.code == -403) {
                //未登录
                user.goLogin();
                return '';
            }
            return '';
        }
    },
    /*
     * 获取某个url字符串中 key的value  比如 xxx.com?a=1&b=2
     */
    getKey: function (url, key) {
        url = url.toString();
        if (url.indexOf('#') >= 0) {
            url = url.substring(0, url.indexOf('#'));
        }
        var value = '';
        var begin = url.indexOf(key + '=');
        if (begin >= 0) {
            var tmp = url.substring(begin + key.length + 1);
            var eqIdx = tmp.indexOf('=');
            var end = 0;
            if (eqIdx >= 0) {
                tmp = tmp.substring(0, eqIdx);
                end = tmp.lastIndexOf('&');
            } else {
                end = tmp.length;
            }
            if (end >= 0) {
                try {
                    value = decodeURIComponent(tmp.substring(0, end));
                } catch (e) {
                    value = tmp.substring(0, end);
                }
            } else {
                try {
                    value = decodeURIComponent(tmp);
                } catch (e) {
                    value = tmp;
                }
            }
        }
        return value;
    },
    getShowData: function (data, index, params) {
        var result = [];
        var precision = 2;
        if (params && params.precision) {
            precision = params.precision;
        }
        for (var i = 0, len = data.length; i < len; i++) {
            result.push(parseFloat(data[i][index]).toFixed(precision));
        }
        return result;
    },
    splitData: function (rawData) {
        var categoryData = [];
        var values = [];
        for (var i = 0; i < rawData.length; i++) {
            categoryData.push(rawData[i].splice(0, 1)[0]);
            values.push(rawData[i]);
        }
        return {
            categoryData: categoryData,
            values: values
        };
    },
    createECharts: function (params) {
        var bigJSON = params.bigJSONFunction(params.json);
        var domId = params.domId;
        var rawData = bigJSON.dataArray;
        var nameArray = bigJSON.nameArray;
        var lineStyleObj = bigJSON.lineStyleObj;
        var data = this.splitData(rawData);
        var seriesConfig = [];
        $.each(nameArray, function (k, v) {
            var lineStyle = {
                normal: {opacity: 0.5}
            };
            if (lineStyleObj && lineStyleObj[v]) {
                lineStyle.normal = $.extend(lineStyle.normal, lineStyleObj[v]);
            }
            var obj = {
                name: v,
                type: 'line',
                data: common.getShowData(data.values, k, params),
                smooth: true,
                lineStyle: lineStyle,
                markLine: bigJSON.markLine || {}
            };
            seriesConfig.push(obj);
        });
        var dom = document.getElementById(domId);
        var myChart = echarts.init(dom);
        var option = {
            title: {
                text: params.text
            },
            backgroundColor: '#eee',
            animation: true,
            legend: {
                bottom: 20,
                left: 'center',
                data: nameArray
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'line'
                }
            },
            toolbox: {
                show: typeof params.toolboxShow == 'undefined' ? true : params.toolboxShow,
                feature: {
                    dataZoom: {
                        show: false
                    },
                    brush: {
                        show: false
                    },
                    myEnlarge: {
                        show: typeof params.enlargeShow == 'undefined' ? true : params.enlargeShow,
                        title: '放大',
                        icon: 'image://http://echarts.baidu.com/images/favicon.png',
                        onclick: function () {
                            console.log(domId + '放大...');
                            common.enlargeECharts(params);
                            if (typeof params.enlarge == 'function') {
                                params.enlarge();
                            }
                        }
                    }
                }
            },
            brush: {
                xAxisIndex: 'all',
                brushLink: 'all',
                outOfBrush: {
                    colorAlpha: 0.1
                }
            },
            grid: [
                {
                    left: '10%',
                    right: '8%',
                    height: '50%'
                },
                {
                    left: '10%',
                    right: '8%',
                    top: '63%',
                    height: '16%'
                }
            ],
            xAxis: [
                {
                    type: 'category',
                    data: data.categoryData,
                    scale: true,
                    boundaryGap: false,
                    axisLine: {onZero: false},
                    splitLine: {
                        show: false
                    },
                    splitNumber: 20,
                    min: 'dataMin',
                    max: 'dataMax'
                },
                {
                    type: 'category',
                    gridIndex: 1,
                    data: data.categoryData,
                    scale: true,
                    boundaryGap: false,
                    axisLine: {onZero: false},
                    axisTick: {show: false},
                    splitLine: {show: false},
                    axisLabel: {show: false},
                    splitNumber: 20,
                    min: 'dataMin',
                    max: 'dataMax'
                }
            ],
            yAxis: [
                {
                    scale: true,
                    splitArea: {
                        show: true
                    }
                },
                {
                    scale: true,
                    gridIndex: 1,
                    splitNumber: 2,
                    axisLabel: {show: false},
                    axisLine: {show: false},
                    axisTick: {show: false},
                    splitLine: {show: false}
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    xAxisIndex: [0, 1],
                    start: 0,
                    end: 100
                },
                {
                    show: true,
                    xAxisIndex: [0, 1],
                    type: 'slider',
                    top: '85%',
                    start: 0,
                    end: 100
                }
            ],
            series: seriesConfig
        };
        myChart.setOption(option, true);
        return myChart;
    },
    enlargeECharts: function (params) {
        var width = $(window).width() - 100;
        var height = width / 1.5;
        if (height >= $(window).height()) {
            height = width / 2;
        }
        var marginTop = $(window).height() - height;
        marginTop = marginTop / 2;
        var html = '';
        html += '<div id="commonEnlarge" style="display: none;" class="enlarge">';
        html += '   <div class="enlarge-bg"></div>';
        html += '   <div id="commonEnlargeContent" style="width: ' + width + 'px; height: ' + height + 'px;margin-top: ' + marginTop + 'px;margin-left: 50px;" class="enlarge-content"></div>';
        html += '   <span id="commonEnlargeClose" title="关闭" class="close warp" style="position: fixed;left: ' + (width) + 'px;top: ' + (marginTop) + 'px;z-index:2;"></span>';
        html += '</div>';
        $('#commonEnlarge').remove();
        $('body').append(html);
        $('#commonEnlarge').fadeIn();
        $(document).keyup(function (event) {
            if (event.keyCode == 27 || event.keyCode == 96) {
                $('#commonEnlarge').fadeOut();
            }
        });
        $('#commonEnlargeClose').on('click', function () {
            $('#commonEnlarge').fadeOut();
        });
        var newParams = {
            domId: 'commonEnlargeContent',
            toolboxShow: false,
            enlargeShow: false
        };
        newParams = $.extend(params, newParams);
        common.createECharts(newParams);
    },
    enlargeCov: function (params) {
        var width = $(window).width() - 100;
        var height = width / 1.5;
        if (height >= $(window).height()) {
            height = width / 2;
        }
        var marginTop = $(window).height() - height;
        marginTop = marginTop / 2;
        var html = '';
        html += '<div id="commonEnlarge" style="display: none;" class="enlarge">';
        html += '   <div class="enlarge-bg"></div>';
        html += '   <div id="commonEnlargeContent" style="width: ' + width + 'px; height: ' + height + 'px;margin-top: ' + marginTop + 'px;margin-left: 50px;padding: 50px;background-color: #fff;" class="enlarge-content"></div>';
        html += '   <span id="commonEnlargeClose" title="关闭" class="close warp" style="position: fixed;left: ' + (width) + 'px;top: ' + (marginTop) + 'px;z-index:2;"></span>';
        html += '</div>';
        $('#commonEnlarge').remove();
        $('body').append(html);
        $('#commonEnlargeContent').html($('#covContent').html()).find('table').show();
        $('#commonEnlarge').fadeIn();
        $(document).keyup(function (event) {
            if (event.keyCode == 27 || event.keyCode == 96) {
                $('#commonEnlarge').fadeOut();
            }
        });
        $('#commonEnlargeClose').on('click', function () {
            $('#commonEnlarge').fadeOut();
        });
    }
};
for (var key in common) {
    if (key) {
        exports[key] = common[key];
    }
}
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};